/*
 AudioPlayer.m
 
 Created by Thong Nguyen on 14/05/2012.
 https://github.com/tumtumtum/audjustable
 
*/

#import "AudioPlayerView.h"

@interface AudioPlayerView()

@end

@implementation AudioPlayerView

// 声明静态单例
+ (AudioPlayerView *)shareHandle:(CGRect)frame
{
    static AudioPlayerView *aPlayer = nil;
    if (aPlayer == nil) {
        aPlayer = [[AudioPlayerView alloc] initWithFrame:frame];
    }
    return aPlayer;
}

- (id)initWithFrame:(CGRect)frame andAudioPlayer:(STKAudioPlayer*)audioPlayerIn
{
    self = [super initWithFrame:frame];
    if (self)
	{
        self.audioPlayer = audioPlayerIn;
        
        self.audioPlayer.delegate = self;
        
        // 播放界面背景
        Myback = [[UIImageView alloc] initWithFrame:self.frame];
        Myback.image = [UIImage imageNamed:@"模糊页面2.jpg"];
        [Myback setContentScaleFactor:[[UIScreen mainScreen] scale]];
        Myback.contentMode =  UIViewContentModeScaleAspectFill;
        Myback.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        Myback.clipsToBounds  = YES;
        [self addSubview:Myback];
        
        
        // 返回按钮
        backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        backButton.frame = CGRectMake(25*ADJUSTWIDTH, 30*ADJUSTWIDTH, SCREEN_HEIGHT*0.04497, SCREEN_HEIGHT*0.04497);
        [backButton setBackgroundImage:[UIImage imageNamed:@"back_image.png"] forState:0];
        [backButton addTarget:self action:@selector(backButtonAct) forControlEvents:UIControlEventTouchUpInside];
        
        // 标题Label
        titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH*0.16, SCREEN_HEIGHT*0.04497, SCREEN_WIDTH*0.5866, SCREEN_HEIGHT*0.04497)];
        titleLabel.font = [UIFont boldSystemFontOfSize:20];
        titleLabel.textColor = [UIColor whiteColor];
        
        
        // 歌手名字
        singerName = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH*0.16, SCREEN_WIDTH*0.16, SCREEN_WIDTH*0.5866, SCREEN_HEIGHT*0.04497)];
        singerName.font = [UIFont boldSystemFontOfSize:15];
        singerName.textColor = [UIColor whiteColor];
        
        
        // 收藏按钮
        CGFloat likeSizeX = SCREEN_WIDTH*0.773333; // 290
        CGFloat likeSizeY = SCREEN_WIDTH*0.08;  // 30
        self.likeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.likeButton.frame = CGRectMake(likeSizeX, likeSizeY, likeSizeY, likeSizeY);
        [self.likeButton setBackgroundImage:[UIImage imageNamed:@"空白.png"] forState:0];
        [self.likeButton addTarget:self action:@selector(collectButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        
        
        // share 按钮
        shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
        shareButton.frame = CGRectMake(SCREEN_WIDTH*0.88, likeSizeY, likeSizeY, likeSizeY);
        [shareButton setBackgroundImage:[UIImage imageNamed:@"share_button.png"] forState:0];
        [shareButton addTarget:self action:@selector(shareButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        
        
        // 播放动画
        CGFloat musicSize = SCREEN_WIDTH*0.7333;
        musicpost = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH*0.13333, SCREEN_WIDTH*0.32, musicSize, musicSize)];
        musicpost.image = [UIImage imageNamed:@"bofang_meitu_1.jpg"];
        musicpost.layer.masksToBounds = YES;
        musicpost.layer.cornerRadius = musicSize/2;
        musicpost.layer.borderWidth = 1.;
        musicpost.layer.borderColor = [[UIColor whiteColor] CGColor];
        // 播放方法
        [self playAnimation];
    
        
        
        // 进度条 slider
		slider = [[UISlider alloc] initWithFrame:CGRectMake(likeSizeY, SCREEN_HEIGHT*0.67466,SCREEN_WIDTH*0.8, SCREEN_WIDTH*0.053333)];
		slider.continuous = YES;
        slider.center = CGPointMake(self.frame.size.width/2, self.frame.size.height-158);
        
        [slider addTarget:self action:@selector(sliderChanged:)
         forControlEvents:UIControlEventValueChanged];
        //滑块图片
        UIImage *thumbImage = [UIImage imageNamed:@"slider.png"];
        slider.backgroundColor = [UIColor clearColor];
        slider.value=0.5;
        slider.minimumValue=0.0;
        slider.maximumValue=1.0;
        //注意这里要加UIControlStateHightlighted的状态，否则当拖动滑块时滑块将变成原生的控件
        [slider setThumbImage:thumbImage forState:UIControlStateHighlighted];
        [slider setThumbImage:thumbImage forState:UIControlStateNormal];
        
        
        //  开始时间
        label = [[UILabel alloc] initWithFrame:CGRectMake(slider.frame.origin.x, slider.frame.origin.y + slider.frame.size.height+5, SCREEN_WIDTH*0.1066666+20, SCREEN_WIDTH*0.053333)];
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:14];
        label.textAlignment = NSTextAlignmentLeft;

        
        //  结束时间
        endtimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(slider.frame.origin.x+slider.frame.size.width-40, label.frame.origin.y, SCREEN_WIDTH*0.1066666+20, SCREEN_WIDTH*0.053333)];
        endtimeLabel.textColor = [UIColor whiteColor];
        endtimeLabel.font = [UIFont systemFontOfSize:14];
        endtimeLabel.textAlignment = NSTextAlignmentLeft;

        
        // 状态label 缓冲中
        statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, label.frame.origin.y+label.frame.size.height-10, frame.size.width, likeSizeY)];
        statusLabel.textAlignment = NSTextAlignmentCenter;
        statusLabel.textColor = [UIColor whiteColor];
        
        
        // 播放按钮
        playButton = [UIButton buttonWithType:UIButtonTypeCustom];
        playButton.frame = CGRectMake(self.frame.size.width/2-64/2, self.frame.size.height-104, 64, 64);
        playButton.center = CGPointMake(self.frame.size.width/2, self.frame.size.height-80);
        [playButton addTarget:self action:@selector(playButtonPressed:)
             forControlEvents:UIControlEventTouchUpInside];

        
        
        
        // 上一曲
        preMusicButton = [UIButton buttonWithType:UIButtonTypeCustom];
        preMusicButton.frame = CGRectMake(playButton.frame.origin.x-60, playButton.frame.origin.y+17, 30, 30);
        [preMusicButton setBackgroundImage:[[UIImage imageNamed:@"iconfont-bofangqishangyiqu.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:0];
        [preMusicButton setTitleColor:[UIColor blackColor] forState:0];
        [preMusicButton addTarget:self action:@selector(PreObjectButton) forControlEvents:UIControlEventTouchUpInside];
        
        
        // 下一曲按钮
        nextMusicButton = [UIButton buttonWithType:UIButtonTypeCustom];
        nextMusicButton.frame = CGRectMake(playButton.frame.origin.x+64+30, playButton.frame.origin.y+17, 30, 30);
        [nextMusicButton setBackgroundImage:[[UIImage imageNamed:@"iconfont-bofangqixiayiqu-3.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:0];
        [nextMusicButton setTitleColor:[UIColor blackColor] forState:0];
        [nextMusicButton addTarget:self action:@selector(nextObjectButton)
                  forControlEvents:UIControlEventTouchUpInside];
        
        
        // 切换 播放模式 按钮
        self.playWayButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.playWayButton.frame = CGRectMake(20, nextMusicButton.frame.origin.y, 30, 30);
        [self.playWayButton addTarget:self action:@selector(playWays:) forControlEvents:UIControlEventTouchUpInside];
        [self.playWayButton setBackgroundImage:[UIImage imageNamed:@"ttpodicon-3.png"] forState:UIControlStateNormal];
        [self addSubview:self.playWayButton];
        

        [self addSubview:self.likeButton];
        [self addSubview:shareButton];
        [self addSubview:singerName];
        [self addSubview:musicpost];
        [self addSubview:titleLabel];
        [self addSubview:nextMusicButton];
        [self addSubview:preMusicButton];
        [self addSubview:backButton];
		[self addSubview:slider];
		[self addSubview:playButton];
        [self addSubview:label];
        [self addSubview:endtimeLabel];
        [self addSubview:statusLabel];
        // 启动播放
		[self setupTimer];
        
        [self updateControls];

    }
	
    return self;
}

// 模式按钮
- (void)playWays:(UIButton *)sender
{
    [self.delegate playWaysChange];
}




// 动画旋转
- (void)playAnimation
{
    //给歌手图片一个效果
    CABasicAnimation *monkeyAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    monkeyAnimation.toValue = [NSNumber numberWithFloat:2.0 *M_PI];
    monkeyAnimation.duration = 1.5;
    monkeyAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    monkeyAnimation.cumulative = NO;
    monkeyAnimation.removedOnCompletion = NO; //No Remove
    monkeyAnimation.repeatCount = FLT_MAX;
    [musicpost.layer addAnimation:monkeyAnimation forKey:@"AnimatedKey"];
    musicpost.layer.speed = 0.1;
    musicpost.layer.beginTime = 0.0;
}

// 赋值方法
- (void)getModel:(ReDetailModel *)model
{
    
    self.model = model;    
    
    // 如果数据包含singerName 则判断
    if (model.singerName) {
        titleLabel.text = model.name;
        singerName.text = model.singerName;
        
        // 音质控制
        if (model.auditionList.count > 1) {
            
            NSDictionary *dic = [model.auditionList objectAtIndex:1];
            NSString *url_string = [dic objectForKey:@"url"];
            self.model.url = url_string;
            
        } else {
            NSDictionary *dic = [model.auditionList objectAtIndex:0];
            NSString *url_string = [dic objectForKey:@"url"];
            self.model.url = url_string;
        }
        
    }else {
        
        titleLabel.text = model.song_name;
        singerName.text = model.singer_name;
        
        if (model.audition_list.count > 1) {
            
            NSDictionary *dic = [model.audition_list objectAtIndex:1];
            NSString *url_string = [dic objectForKey:@"url"];
            self.model.url = url_string;
        } else {
            
            NSDictionary *dic = [model.audition_list objectAtIndex:0];
            NSString *url_string = [dic objectForKey:@"url"];
            self.model.url = url_string;
        }
    }

}



// 下一曲
- (void)nextObjectButton
{
    [self.delegate nextButton];
}
// 上一曲
- (void)PreObjectButton
{
    [self.delegate preButton];
}

// 模态消失 页面消失
- (void)backButtonAct
{
    [self.delegate dismissViewController];
}

// 进度条
-(void) sliderChanged:(UISlider *)mySlider
{
    if (slider) {
        UISlider *processSlider = mySlider;
        [self.audioPlayer seekToTime:processSlider.value];
    }
    
    [self updateControls];
    
}

// 时间值
-(void) setupTimer
{
	timer = [NSTimer timerWithTimeInterval:0.001 target:self selector:@selector(tick) userInfo:nil repeats:YES];
	[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

-(void) tick
{
    if (slider) {
        slider.maximumValue = self.audioPlayer.duration;
        slider.value = self.audioPlayer.progress;
        NSInteger proMin = (NSInteger)self.audioPlayer.progress / 60;
        NSInteger proSec = (NSInteger)self.audioPlayer.progress % 60;
        NSInteger durMin = (NSInteger)self.audioPlayer.duration / 60;
        NSInteger durSec = (NSInteger)self.audioPlayer.duration % 60;
        label.text = [NSString stringWithFormat:@"%02ld:%02ld", (long)proMin, (long)proSec];
        endtimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld",(long)durMin, (long)durSec];
    }
    // 如果播放器状态停止了 就自动播放下一曲
    if (self.audioPlayer.state == STKAudioPlayerStateStopped){
        slider.value = 0;
        slider.minimumValue = 0;
        slider.maximumValue = 0;
        label.text = @"";
        
        // 通知中心
        NSNotificationCenter *play = [NSNotificationCenter defaultCenter];
        [play postNotificationName:@"PLAY" object:nil];
        
        return;
    }
    statusLabel.text = self.audioPlayer.state == STKAudioPlayerStateBuffering ? @"缓冲中..." : @"";

}

// 播放与暂停
-(void) playButtonPressed:(UIButton *)sender
{
    UIButton *button = sender;
    if (self.audioPlayer.state == STKAudioPlayerStatePaused) {
        [button setBackgroundImage:[UIImage imageNamed:@"iconfont-iconfont32.png"] forState:0];
        [self.audioPlayer resume]; 
        
        // 播放暂停
        CFTimeInterval pausedTime = [musicpost.layer timeOffset];
        musicpost.layer.speed = 0.1;
        musicpost.layer.timeOffset = 0.0;
        musicpost.layer.beginTime = 0.0;
        CFTimeInterval timeSincePause = [musicpost.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
        musicpost.layer.beginTime = timeSincePause;
        
        
    } else if (self.audioPlayer.state == STKAudioPlayerStatePlaying) {
        
        [button setBackgroundImage:[UIImage imageNamed:@"iconfont-bofang-4.png"] forState:0];
        [self.audioPlayer pause];
        
        // 播放回复
        CFTimeInterval pausedTime = [musicpost.layer convertTime:CACurrentMediaTime() fromLayer:nil];
        musicpost.layer.speed = 0.0;
        musicpost.layer.timeOffset = pausedTime;        
        
    } else if (self.audioPlayer.state == STKAudioPlayerStateReady) {
        
        [button setBackgroundImage:[UIImage imageNamed:@"iconfont-iconfont32.png"] forState:0];
        
        //[self beginAction:nil];
    }
    
}



// 记录 播放按钮状态
-(void) updateControls
{
    
    if (self.audioPlayer.state == STKAudioPlayerStatePaused){
        
        
        [playButton setBackgroundImage:[UIImage imageNamed:@"iconfont-bofang-4.png"] forState:0];
        
    }else if (self.audioPlayer.state & STKAudioPlayerStatePlaying){
        
        
        [playButton setBackgroundImage:[UIImage imageNamed:@"iconfont-iconfont32.png"] forState:0];
        
        
    }
    
    [self tick];
}


-(void) audioPlayer:(STKAudioPlayer*)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState
{
    [self updateControls];
    
    
}

// 收藏按钮
- (void)collectButtonAction:(UIButton *)sender
{
    
    [self.delegate collectMusic:sender];
}


// 分享按钮
- (void)shareButtonAction:(UIButton *)sender
{
    
    [self.delegate shareMusicButton];
}

/// Raised when an item has started playing
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didStartPlayingQueueItemId:(NSObject*)queueItemId
{
}
/// Raised when an item has finished buffering (may or may not be the currently playing item)
/// This event may be raised multiple times for the same item if seek is invoked on the player
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject*)queueItemId
{
}
/// Raised when the state of the player has changed


/// Raised when an item has finished playing
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishPlayingQueueItemId:(NSObject*)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
}
/// Raised when an unexpected and possibly unrecoverable error has occured (usually best to recreate the STKAudioPlauyer)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode
{
}



@end
